#!coding:utf-8
# vim: tabstop=4 shiftwidth=4 softtabstop=4
from lxml import etree
import logging

from cvirt.cnode.libvirtXmlObject.baseDomain import GuestDevice

LOG = logging.getLogger(__name__)

"""
    @author jay.han
"""
class GuestGraphics(GuestDevice):
    ROOT_NAME = "graphics"
    TYPE_SDL = "sdl"
    TYPE_VNC = "vnc"
    TYPE_RDP = "rdp"
    TYPE_SPICE = "spice"

    def __init__(self, parse_xml=None, **kw):
        super(GuestGraphics, self).__init__(parse_xml=parse_xml,**kw)

        self.type = "vnc"
        self.autoport = False
        self.port = None
        self.keymap = None
        self.listen = '0.0.0.0'
        self.image_comp = 'auto_glz'
        self.streaming = 'all'
        self.jpeg = 'always'
        self.passwd = None

    def _parse_xml(self, xmldoc):
        self.autoport = True if xmldoc.get('autoport') == 'yse' else False
        self.type = xmldoc.get('type')
        self.listen = xmldoc.get('listen')
        self.port = xmldoc.get("port")

        if self.type != 'spice':
            self.clear_spice()
        else:
            for c in xmldoc.getchildren():
                if c.tag == 'image':
                    self.image_comp = c.get('compression')
                elif c.tag == 'jpeg':
                    self.jpeg = c.get('compression')
                elif c.tag == 'streaming':
                    self.streaming = c.get('mode')


    def clear_spice(self):
        self.image_comp = None
        self.streaming = None
        self.jpeg = None

    def _get_xml_config(self, root):
        dev = root
        dev.set("type", self.type)
        if self.autoport:
            dev.set("autoport", "yes")
        else:
            dev.set("autoport", "no")
        if self.keymap:
            dev.set("keymap", self.keymap)
        if self.listen:
            dev.set("listen", self.listen)
        if self.port:
            dev.set('port',str(self.port))
        if self.passwd:
            dev.set('passwd',str(self.passwd))

        if self.type == 'spice':
            dev.append(etree.Element("image", compression=self.image_comp))
            dev.append(etree.Element("jpeg", compression=self.jpeg))
            dev.append(etree.Element("streaming",mode=self.streaming))

        return dev

class GraphicVideo(GuestDevice):
    ROOT_NAME = "video"
    _model_types = [ "cirrus", "vga", "vmvga", "xen", "qxl"]

    def __init__(self, parse_xml=None, **kw):
        self.type='qxl'
        self.vram='65536'
        # self.ram = '65536'
        self.heads = '1'
        super(GraphicVideo, self).__init__(parse_xml=parse_xml,**kw)

    def _parse_xml(self, xmldoc):
        xmldoc = xmldoc.find('./model')
        self.type = xmldoc.get('type')
        # self.ram = xmldoc.get('ram')
        self.vram = xmldoc.get('vram')
        self.heads = xmldoc.get('heads')

    def _get_xml_config(self, root):
        dev= root
        dev.append(etree.Element("model",type=self.type,vram=self.vram,heads=self.heads))
        return dev